package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EazyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private EazyIdClient eazyIdClient;
    @Autowired
    private StorageClient storageClient;

    /*
    启动TM(Transaction Manager)
    连接事务协调器 TC
    注册全局事务
    启动本地 RM(Resourse Manager)
     */
    @GlobalTransactional
    @Override
    public void create(Order order) {
        //生成一个订单id
        //远程调用发号器，获得一个全局唯一id
        String strid = eazyIdClient.nextId("order_business");
        Long id = Long.parseLong(strid);
        //保存订单
        order.setId(id);
        orderMapper.create(order);
        log.info("保存订单成功，order="+order);

        // 远程调用storage，修改库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用account，修改账户余额
        accountClient.decrease(order.getUserId(), order.getMoney());

    }
}
